package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.util.ZipUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.node.LayuiTreeNode;
import cn.stylefeng.guns.base.pojo.node.ZTreeNode;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.entity.GcgWsjd;
import cn.stylefeng.guns.sys.modular.system.entity.GcgWsjdShenpi;
import cn.stylefeng.guns.sys.modular.system.entity.GcgWsjdShenpiXq;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.params.GcgWsjdParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskStatusParam;
import cn.stylefeng.guns.sys.modular.system.model.params.GcgWsjdShenpiParam;
import cn.stylefeng.guns.sys.modular.system.model.result.GcgWsjdResult;
import cn.stylefeng.guns.sys.modular.system.service.GcgWsjdService;
import cn.stylefeng.guns.sys.modular.system.service.PushMsgService;
import cn.stylefeng.guns.sys.modular.system.service.TaskStatusService;
import cn.stylefeng.guns.sys.modular.system.service.WsjdService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.security.GeneralSecurityException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 网上建店信息gcg_wsjd 服务实现类
 * </p>
 *
 * @author liuy
 * @since 2021-05-18
 */
@Service
public class GcgWsjdServiceImpl extends ServiceImpl<GcgWsjdMapper, GcgWsjd> implements GcgWsjdService {

    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;
    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private String port;
    @Value("${spring.mail.protocol}")
    private String protocol;
    @Resource
    private TaskStatusService taskStatusService;
    @Resource
    private TaskFlowMapper taskFlowMapper;
    @Resource
    private GcgWsjdTakeawayMapper gcgWsjdTakeawayMapper;
    @Resource
    private PushMsgService pushMsgService;


    @Resource
    private GcgWsjdShenpiMapper gcgWsjdShenpiMapper;
    @Resource
    private GcgWsjdShenpiXqMapper gcgWsjdShenpiXqMapper;
    @Resource
    private GcgWsjdMapper gcgWsjdMapper;
    @Resource
    private GcgWsjdYinhangkaMapper yinhangkaMapper;

    @Override
    public void add(GcgWsjdParam param) {
        GcgWsjd entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(GcgWsjdParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(GcgWsjdParam param) {
        //gcgWsjdShenpixiangId    gcgWsjdId
        Long gcgWsjdId=param.getGcgWsjdId();
        Long gcgWsjdShenpixiangId=param.getGcgWsjdShenpixiangId();
        String miaoshu=param.getMiaoshu();
        //更新审批状态
        GcgWsjdShenpi shenpi=gcgWsjdShenpiMapper.selectOne(new QueryWrapper<GcgWsjdShenpi>().eq("gcg_wsjd_id",gcgWsjdId).eq("type",1));
        if(ToolUtil.isNotEmpty(shenpi)){
            //审核状态,1->待审批，2->被驳回， 3->通过
            shenpi.setShStatus("2");
            shenpi.setShenpiYijina("审核被驳回!");
            shenpi.setShenpiShijian(new Date());
            gcgWsjdShenpiMapper.updateById(shenpi);
            Long shenpiId=shenpi.getGcgWsjdShenpiId();

            //添加驳回数据到gcg_wsjd_shenpi_xq表中 判断是否有数据有就更新
            GcgWsjdParam wsjdParam=new GcgWsjdParam();
            wsjdParam.setGcgWsjdShenpixiangId(gcgWsjdShenpixiangId);
            wsjdParam.setGcgWsjdId(gcgWsjdId);
            List<Map<String,Object>> list=gcgWsjdMapper.selectMenuTree(wsjdParam);
            if(list.size()>0){
                GcgWsjdShenpiXq xqs= gcgWsjdShenpiXqMapper.selectOne(new QueryWrapper<GcgWsjdShenpiXq>().eq("gcg_wsjd_shenpi_id",shenpiId)
                        .eq("gcg_wsjd_shenpixiang_id",gcgWsjdShenpixiangId));
                if(ToolUtil.isNotEmpty(xqs)){
                    xqs.setMiaoshu(miaoshu);
                    xqs.setUpdateTime(new Date());
                    xqs.setUpdateUser(LoginContextHolder.getContext().getUserId());
                    gcgWsjdShenpiXqMapper.updateById(xqs);
                }else{
                    GcgWsjdShenpiXq xq = new GcgWsjdShenpiXq();
                    xq.setGcgWsjdShenpiXqId(UUIDUtils.getId());
                    xq.setGcgWsjdShenpiId(shenpiId);
                    xq.setGcgWsjdShenpixiangId(gcgWsjdShenpixiangId);
                    xq.setMiaoshu(miaoshu);
                    xq.setCreateUser(LoginContextHolder.getContext().getUserId());
                    xq.setCreateTime(new Date());
                    gcgWsjdShenpiXqMapper.insert(xq);
                }

            }else {
                GcgWsjdShenpiXq xq = new GcgWsjdShenpiXq();
                xq.setGcgWsjdShenpiXqId(UUIDUtils.getId());
                xq.setGcgWsjdShenpiId(shenpiId);
                xq.setGcgWsjdShenpixiangId(gcgWsjdShenpixiangId);
                xq.setMiaoshu(miaoshu);
                xq.setCreateUser(LoginContextHolder.getContext().getUserId());
                xq.setCreateTime(new Date());
                gcgWsjdShenpiXqMapper.insert(xq);
            }

        }


//        GcgWsjd oldEntity = getOldEntity(param);
//        GcgWsjd newEntity = getEntity(param);
//        ToolUtil.copyProperties(newEntity, oldEntity);
//        this.updateById(newEntity);
    }

    @Override
    public GcgWsjdResult findBySpec(GcgWsjdParam param) {
        return null;
    }

    @Override
    public List<GcgWsjdResult> findListBySpec(GcgWsjdParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(GcgWsjdParam param) {
        if(ToolUtil.isEmpty(param.getShStatus())){
            param.setShStatus("1");
        }
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<GcgWsjdResult> customList(GcgWsjdParam param) {
        List<GcgWsjdResult> list = baseMapper.customList(param);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void expExcel(HttpServletResponse response, GcgWsjdParam wsjdParam) {

        //Integer  flag=0;
        try {
            //设置日期格式

            DecimalFormat format = new DecimalFormat("0.00");
            String[] ids = wsjdParam.getIds().split(",");

            wsjdParam.setIdss(ids);
            List<File> srcfile = new ArrayList<File>();
            List<Integer> projectIds = new ArrayList<>();
            Set<String> set = new HashSet<>();
            // 查询数据
            List<GcgWsjdResult> listWsjd = baseMapper.customList(wsjdParam);
            for (GcgWsjdResult gcgWsjdResult : listWsjd) {
                projectIds.add(gcgWsjdResult.getGcgProjectId());
                set.add(gcgWsjdResult.getKhMing());
            }

            List<GcgWsjdResult> listWsjd1 = baseMapper.customList(wsjdParam);
            List<String>urlList=new ArrayList<>();

            List<String>fileNameList=new ArrayList<>();

            Iterator<String> it = set.iterator();
            //判断是否有下一个
            int num=0;
            while(it.hasNext()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String number = sdf.format(new Date());
                System.out.println("number:"+number);
                num++;
                String khr=it.next();
                wsjdParam.setKhMing(khr);
                List<GcgWsjdResult> listWsjd2 = baseMapper.customList(wsjdParam);
                String fileName = number+num;
                String path = "D:\\mt\\";
                File f = new File(path);
                if (!f.exists()) {
                    f.mkdirs(); //创建目录
                }
                String url = path + fileName + ".xls";
                System.out.println("url:" + url);
                String dm="";
                for (int i = 0; i < listWsjd2.size(); i++) {
                    dm=dm+listWsjd2.get(i).getMingcheng()+" ";
                }
                System.out.println("dm:"+dm);
                //账户信息数据
                List<String[]> dataset = new ArrayList<>();
                // for (int i = 0; i < listWsjd.size(); i++) {
                String[] arr1 = new String[8];
                arr1[0] = dm;
                arr1[1] = listWsjd2.get(0).getKhHang() == null ? "" : listWsjd2.get(0).getKhHang();
                arr1[2] = listWsjd2.get(0).getKhMing() == null ? "" : listWsjd2.get(0).getKhMing();
                arr1[3] = listWsjd2.get(0).getKhZhanghao() == null ? "" : listWsjd2.get(0).getKhZhanghao();
                arr1[4] = listWsjd2.get(0).getKhSfz() == null ? "" : listWsjd2.get(0).getKhSfz();
                arr1[5] = listWsjd2.get(0).getKhTel() == null ? "" : listWsjd2.get(0).getKhTel();
                arr1[6] = listWsjd2.get(0).getCwName() == null ? "" : listWsjd2.get(0).getCwName();
                arr1[7] = listWsjd2.get(0).getCwTel() == null ? "" : listWsjd2.get(0).getCwTel();
                dataset.add(arr1);

                //}
                List<String[]> dataset1 = new ArrayList<>();
                for (int i = 0; i < listWsjd2.size(); i++) {
                    String[] arr = new String[8];
                    arr[0] = i + 1 + "";
                    arr[1] = listWsjd2.get(i).getMingcheng() == null ? "" : listWsjd2.get(i).getMingcheng();
                    arr[2] = listWsjd2.get(i).getPinpai() == null ? "半天妖" : listWsjd2.get(i).getPinpai();
                    arr[3] = listWsjd2.get(i).getFarenXingming() == null ? "" : listWsjd2.get(i).getFarenXingming();
                    arr[4] = listWsjd2.get(i).getAddress() == null ? "" : listWsjd2.get(i).getAddress();
                    arr[5] = listWsjd2.get(i).getMdTel() == null ? "" : listWsjd2.get(i).getMdTel();
                    arr[6] = listWsjd2.get(i).getGuishu() == null ? "济南半天妖餐饮有限公司" : listWsjd2.get(i).getGuishu();
                    arr[7] = listWsjd2.get(i).getMdYysj() == null ? "" : listWsjd2.get(i).getMdYysj();
                    dataset1.add(arr);
                }
                //账户信息表头
                String[] handers1 = {"门店ID+门店名称", "开户行(银行名称+省+支行)", "开户名(对私)", "银行帐号", "开户人身份证号码", "开户人银行卡预留手机号", "财务联系人姓名(用于打款短信接收)", "财务联系人电话(用于打款短信接收)"};
                //门店详情表头
                String[] handers2 = {"序号", "分店名称", "对外门店名称", "法人", "详细地址", "订餐电话", "公司归属", "每日营业时间"};
                //对象

                ExcelExp fymx = new ExcelExp("账户信息", handers1, dataset);
                ExcelExp mdxq = new ExcelExp("门店详情", handers2, dataset1);
                List<ExcelExp> mysheet = new ArrayList<>();
                mysheet.add(fymx);
                mysheet.add(mdxq);
                urlList.add(url);
                fileNameList.add(fileName);
                //生成sheet
                ExcelUtil.exportManySheetExcel(url, mysheet);
                //下载sheet
                ExcelUtil.getExcel(url, fileName, response);



            }
            for (String s : urlList) {
                System.out.println("url:"+s);
            }
//            WarnMesssgeData warnMes = new WarnMesssgeData();
//            //邮件标题
//            warnMes.setSubject("半天妖建店");
//            //邮件内容
//            warnMes.setContent("报表见附件");
//            //文件名称
//            warnMes.setFileName("xls");
//            //文件地址
//
//            warnMes.setFileAddress(urlList);
//            //收件人地址
//            warnMes.setEmail(wsjdParam.getEmail());
//            //发送邮件
//            sendExcelEmail(warnMes);

            // 由哪个邮箱发送
            String formMail = username;
            // QQ邮箱>设置>账户 开启POP3/SMTP服务 查看smtp密码
            String smtpPassword = password;

            // 发送人邮箱地址
            String descMail = wsjdParam.getEmail();
            String contentType = "text/html;charset=UTF-8";

            String subject = "半天妖建店";
            String content = "报表见附件";
            File[] files = new File[urlList.size()];

            for (int i = 0; i < urlList.size(); i++) {
                files[i] = new File(urlList.get(i));
            }

            sendQQMail(formMail, descMail, subject, content, files, contentType, smtpPassword);

            for (String id : ids) {
              GcgWsjd wsjd= gcgWsjdMapper.selectById(id);
              if(ToolUtil.isNotEmpty(wsjd)){
                  wsjd.setYjzt(1);
                  wsjd.setFjr(username);
                  wsjd.setSjr(descMail);
                  wsjd.setFsdm(wsjd.getMingcheng());
                  String date= DateUtil.getNow();
                  wsjd.setFssj(date);
                  gcgWsjdMapper.updateById(wsjd);

                  //同步工程网上建店任务
                  TaskStatusParam taskStatusParam = new TaskStatusParam();
                  taskStatusParam.setProId(wsjd.getGcgProjectId());
                  taskStatusParam.setTaskId(36);
                  taskStatusParam.setStatus(1);
                  taskStatusParam.setContent("已确认");
                  taskStatusParam.setCreateId(LoginContextHolder.getContext().getUserId());
                  taskStatusParam.setCreateName(LoginContextHolder.getContext().getUser().getName());
                  taskStatusService.add(taskStatusParam);
                  // flow表新增数据
                  TaskFlow taskFlow = new TaskFlow();
                  taskFlow.setProId(wsjd.getGcgProjectId());
                  taskFlow.setTaskId(36);
                  taskFlow.setStatus(1);
                  taskFlow.setTaskName("网上建店");
                  taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
                  taskFlow.setCreateTime(new Date());
                  taskFlowMapper.add(taskFlow);
              }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<GcgWsjdResult> dmList() {
        return baseMapper.dmList();
    }

    @Override
    public List<LayuiTreeNode> layuiTree() {
        return baseMapper.layuiTree();
    }

    @Override
    public List<Map<String, Object>> selectMenuTree(GcgWsjdParam wsjdParam) {
        return baseMapper.selectMenuTree(wsjdParam);
    }

    @Override
    public List<ZTreeNode> menuTreeList() {
        return baseMapper.menuTreeList();
    }
    /**
     * 发送邮件设置
     *
     */
    public  void sendQQMail(String formMail, String descMail, String subject, String content, File[] files,
                                  String contentType, String password) throws MessagingException, UnsupportedEncodingException {
        Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", host);
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", protocol);
        //端口
        prop.setProperty("mail.smtp.port", port);
        Session session = Session.getInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(formMail, password);
            }
        });
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(formMail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(descMail));
            message.setSubject(subject);

            // 是否存在附件
            if (null != files && files.length > 0) {
                MimeMultipart multipart = new MimeMultipart();

                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(content, contentType);
                multipart.addBodyPart(contentPart);

                for (File file : files) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    DataHandler dh2 = new DataHandler(new FileDataSource(file));
                    attachment.setDataHandler(dh2);
                    attachment.setFileName(MimeUtility.encodeText(dh2.getName()));
                    multipart.addBodyPart(attachment);
                }
                multipart.setSubType("mixed");

                message.setContent(multipart);
                message.saveChanges();
            }
            // 普通
            else {
                message.setContent(content, contentType);
            }

            Transport transport = session.getTransport();
            transport.connect(formMail, password);
            Transport.send(message);
        } catch (UnsupportedEncodingException e) {
            throw e;
        } catch (NoSuchProviderException e) {
            throw e;
        } catch (MessagingException e) {
            throw e;
        }

    }



    private Serializable getKey(GcgWsjdParam param) {
        return param.getGcgWsjdId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private GcgWsjd getOldEntity(GcgWsjdParam param) {
        return this.getById(getKey(param));
    }

    private GcgWsjd getEntity(GcgWsjdParam param) {
        GcgWsjd entity = new GcgWsjd();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 支付宝列表
     *
     * @param gcgWsjd
     * @return
     */
    @Override
    public Page<Map<String, Object>> getZfb(GcgWsjd gcgWsjd) {
        Page page = LayuiPageFactory.defaultPage();
        return baseMapper.getZfb(page, gcgWsjd);
    }

    /**
     * 支付宝审批通过
     *
     * @param
     */
    @Override
    public void zfbPass(String id) {
        GcgWsjdShenpi gcgWsjdShenpi = new GcgWsjdShenpi();
        gcgWsjdShenpi.setGcgWsjdId(Long.parseLong(id));
        gcgWsjdShenpi.setType(2);//支付宝
        gcgWsjdShenpi.setShStatus("3");//审核状态,1->待审批，2->被驳回， 3->通过
        gcgWsjdShenpi.setShenpiRen(LoginContextHolder.getContext().getUser().getName());//审批人
        gcgWsjdShenpi.setShenpiShijian(new Date());//审批时间
        gcgWsjdShenpi.setUpdateUser(LoginContextHolder.getContext().getUserId());
        gcgWsjdShenpi.setUpdateTime(new Date());
        gcgWsjdShenpiMapper.zfbPass(gcgWsjdShenpi);
    }

    /**
     * 支付宝审批驳回列表
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> rejectList(Long gcgWsjdId) {
        List<Map<String, Object>> maps = this.baseMapper.rejectList(gcgWsjdId);

//        if (maps == null) {
//            maps = new ArrayList<>();
//        }

//        //修复菜单查询bug，带条件的暂时先父级置为0
//            if (maps.size() > 0) {
//
//                //将pcode置为root
//                for (Map<String, Object> menu : maps) {
//                    menu.put("pcode", "0");
//                }
//            }


//        //创建根节点
//        Menu menu = new Menu();
//        menu.setMenuId(-1L);
//        menu.setName("根节点");
//        menu.setCode("0");
//        menu.setPcode("-2");
//        maps.add(BeanUtil.beanToMap(menu));

        return maps;
    }

    /**
     * 支付宝审批驳回
     */
    @Override
    public void zfbReject(Long gcgWsjdId, String data) {

        //查询审批id
        Long shenpiId = gcgWsjdShenpiMapper.getSpId(gcgWsjdId);

        if (ToolUtil.isNotEmpty(data)){
            //删除审批详情表相关数据
            gcgWsjdShenpiXqMapper.delete(new QueryWrapper<GcgWsjdShenpiXq>().eq("gcg_wsjd_shenpi_id",shenpiId));

            List<GcgWsjdShenpiParam> list = JSON.parseArray(data, GcgWsjdShenpiParam.class);
            for (GcgWsjdShenpiParam gcgWsjdShenpiParam: list) {
                //审批详情表新增数据
                GcgWsjdShenpiXq gcgWsjdShenpiXq = new GcgWsjdShenpiXq();
                gcgWsjdShenpiXq.setGcgWsjdShenpiId(shenpiId);
                gcgWsjdShenpiXq.setGcgWsjdShenpixiangId(gcgWsjdShenpiParam.getGcgWsjdShenpiXiangId());
                gcgWsjdShenpiXq.setMiaoshu(gcgWsjdShenpiParam.getMiaoshu());
                gcgWsjdShenpiXq.setCreateTime(new Date());
                gcgWsjdShenpiXq.setCreateUser(LoginContextHolder.getContext().getUserId());
                gcgWsjdShenpiXqMapper.insert(gcgWsjdShenpiXq);
            }

            //审批表修改状态
            GcgWsjdShenpi gcgWsjdShenpi = new GcgWsjdShenpi();
            gcgWsjdShenpi.setGcgWsjdId(gcgWsjdId);
            gcgWsjdShenpi.setType(2);//支付宝
            gcgWsjdShenpi.setShStatus("2");//审核状态,1->待审批，2->被驳回， 3->通过
            gcgWsjdShenpi.setShenpiRen(LoginContextHolder.getContext().getUser().getName());//审批人
            gcgWsjdShenpi.setShenpiShijian(new Date());//审批时间
            gcgWsjdShenpi.setUpdateUser(LoginContextHolder.getContext().getUserId());
            gcgWsjdShenpi.setUpdateTime(new Date());
            gcgWsjdShenpiMapper.zfbPass(gcgWsjdShenpi);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reject(Long gcgWsjdId, String data) {

        //查询审批id
        Long shenpiId = null;

        GcgWsjdShenpi shenpi=gcgWsjdShenpiMapper.selectOne(new QueryWrapper<GcgWsjdShenpi>().eq("gcg_wsjd_id",gcgWsjdId).eq("type",1));
        if(ToolUtil.isNotEmpty(shenpi)){
            shenpiId=shenpi.getGcgWsjdShenpiId();
            gcgWsjdShenpiXqMapper.delete(new QueryWrapper<GcgWsjdShenpiXq>().eq("gcg_wsjd_shenpi_id",shenpiId));
        }

        if (ToolUtil.isNotEmpty(data)){

            List<GcgWsjdShenpiParam> list = JSON.parseArray(data, GcgWsjdShenpiParam.class);
            String reason = null;
            for (GcgWsjdShenpiParam gcgWsjdShenpiParam: list) {
                reason = gcgWsjdShenpiParam.getMiaoshu();
                //审批详情表新增数据
                GcgWsjdShenpiXq gcgWsjdShenpiXq = new GcgWsjdShenpiXq();
                //gcgWsjdShenpiXq.setGcgWsjdShenpiXqId(UUIDUtils.getId());
                gcgWsjdShenpiXq.setGcgWsjdShenpiId(shenpiId);
                gcgWsjdShenpiXq.setGcgWsjdShenpixiangId(gcgWsjdShenpiParam.getGcgWsjdShenpiXiangId());
                gcgWsjdShenpiXq.setMiaoshu(gcgWsjdShenpiParam.getMiaoshu());
                gcgWsjdShenpiXq.setCreateTime(new Date());
                gcgWsjdShenpiXq.setCreateUser(LoginContextHolder.getContext().getUserId());
                gcgWsjdShenpiXqMapper.insert(gcgWsjdShenpiXq);
            }

            //审批表修改状态
            GcgWsjdShenpi gcgWsjdShenpi = new GcgWsjdShenpi();
            gcgWsjdShenpi.setGcgWsjdId(gcgWsjdId);
            gcgWsjdShenpi.setGcgWsjdShenpiId(shenpiId);
            gcgWsjdShenpi.setType(1);//美团团购
            gcgWsjdShenpi.setShStatus("2");//审核状态,1->待审批，2->被驳回， 3->通过
            gcgWsjdShenpi.setShenpiYijina("驳回");
            gcgWsjdShenpi.setShenpiRen(LoginContextHolder.getContext().getUser().getName());//审批人
            gcgWsjdShenpi.setShenpiShijian(new Date());//审批时间
            gcgWsjdShenpi.setUpdateUser(LoginContextHolder.getContext().getUserId());
            gcgWsjdShenpi.setUpdateTime(new Date());
            int i = gcgWsjdShenpiMapper.updateById(gcgWsjdShenpi);

            if (i > 0){
                //推送消息
                String now = DateUtil.getNow();//当前时间
                //获取当前店名
                Map map = gcgWsjdTakeawayMapper.getDm(gcgWsjdId);
                String dm = null;
                String phone = null;
                if (ToolUtil.isNotEmpty(map)){
                    if (ToolUtil.isNotEmpty(map.get("mingcheng"))){
                        dm = map.get("mingcheng").toString();
                    }
                    if(ToolUtil.isNotEmpty(map.get("phone"))){
                        phone = map.get("phone").toString();
                    }
                }

                if (ToolUtil.isNotEmpty(phone)){
                    //查询当前店审核状态(type: 1 美团团购2 支付宝 3 外卖)
                    String shStatus = gcgWsjdTakeawayMapper.getStatus(gcgWsjdId, 1);
                    GcgWsjd gcgWsjd = new GcgWsjd();
                    gcgWsjd.setMingcheng(dm);
                    gcgWsjd.setGcgProjectId(Integer.valueOf(map.get("gcgProjectId").toString()));
                    gcgWsjd.setGcgWsjdId(Long.valueOf(map.get("gcgWsjdId").toString()));
                    gcgWsjd.setYaoma(map.get("yaoma").toString());
                    gcgWsjd.setShStatus(shStatus);
                    gcgWsjd.setReason(reason);

                    //推送小妖app信息，即时通讯
                    pushMsgService.mttgToIM(gcgWsjd, phone, "驳回", now);
                }
            }
        }

    }

    @Override
    public List<ZTreeNode> rejectTreeList() {
        return baseMapper.rejectTreeList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveKhr(GcgWsjdParam param) {
        Long  gcgWsjdId=param.getGcgWsjdId();
        Long gcgWsjdYinhangkaId=param.getGcgWsjdYinhangkaId();
        GcgWsjdYinhangka ka=yinhangkaMapper.selectById(gcgWsjdYinhangkaId);
        if(ToolUtil.isNotEmpty(ka)){
            String xm=ka.getKhMing();
            String yhk=ka.getKhZhanghao();
            GcgWsjd wsjd=baseMapper.selectById(gcgWsjdId);
            if(ToolUtil.isNotEmpty(wsjd)){
                wsjd.setYhkName(xm);
                wsjd.setYhkHao(yhk);
                wsjd.setGcgWsjdYinhangkaId(gcgWsjdYinhangkaId);
                baseMapper.updateById(wsjd);
            }

        }
    }

    /**
     * 批量下载图片
     * @param ids
     * @param request
     * @param response
     */
    @Override
//    public void btnDown(String ids, HttpServletRequest request, HttpServletResponse response) throws Exception {
//        try {
//            String id[] = ids.split(",");
//            //查图片
//            List<GcgWsjd> pics = this.baseMapper.selectPic(id);
//
//            //多个图片下载地址
//            File fileMemu = new File("D:/wsjd/zfb/zfbtp/");//输入要删除文件目录的绝对路径
//            deleteFile(fileMemu);
//
//            //多个图片下载地址
//            for (int i = 0; i < pics.size(); i++) {
//
//                if (ToolUtil.isNotEmpty(pics.get(i).getYingyeZhizhao())){
//                    //根据图片地址构建URL
//                    URL url = new URL(pics.get(i).getYingyeZhizhao());//营业执照
//                    URLConnection conn = url.openConnection();
//                    conn.setReadTimeout(10000);
//                    conn.setConnectTimeout(10000);
//                    conn.connect();
//                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
//                    //创建目录和图片
//                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());
//                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "营业执照" + i + ".jpg");
//                    if (!pathFile.exists()) {
//                        pathFile.mkdirs();
//                        file.createNewFile();
//                    }
//                    if (!file.exists()) {
//                        file.createNewFile();
//                    }
//                    //通过流复制图片
//                    FileOutputStream fileOutputStream = new FileOutputStream(file);
//                    ByteArrayOutputStream output = new ByteArrayOutputStream();
//                    byte[] buffer = new byte[1024];
//                    int length;
//                    while ((length = dataInputStream.read(buffer)) > 0) {
//                        output.write(buffer, 0, length);
//                    }
//                    fileOutputStream.write(output.toByteArray());
//                    dataInputStream.close();
//                    fileOutputStream.close();
//
//                    //删除服务器上的临时文件
//                    File deleteFile = new File(pics.get(i).getMingcheng());
//                    deleteFile.delete();
//                }
//
//            }
//
//            for (int i = 0; i < pics.size(); i++) {
//
//                if (ToolUtil.isNotEmpty(pics.get(i).getShipinXkz())){
//                    //根据图片地址构建URL
//                    URL url = new URL(pics.get(i).getShipinXkz());//食品经营许可证
//                    URLConnection conn = url.openConnection();
//                    conn.setReadTimeout(10000);
//                    conn.setConnectTimeout(10000);
//                    conn.connect();
//                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
//                    //创建目录和图片
//                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
//                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "食品经营许可证" + i + ".jpg");
//                    if (!pathFile.exists()) {
//                        pathFile.mkdirs();
//                        file.createNewFile();
//                    }
//                    if (!file.exists()) {
//                        file.createNewFile();
//                    }
//                    //通过流复制图片
//                    FileOutputStream fileOutputStream = new FileOutputStream(file);
//                    ByteArrayOutputStream output = new ByteArrayOutputStream();
//                    byte[] buffer = new byte[1024];
//                    int length;
//                    while ((length = dataInputStream.read(buffer)) > 0) {
//                        output.write(buffer, 0, length);
//                    }
//                    fileOutputStream.write(output.toByteArray());
//                    dataInputStream.close();
//                    fileOutputStream.close();
//                }
//
//            }
//            for (int i = 0; i < pics.size(); i++) {
//
//                if (ToolUtil.isNotEmpty(pics.get(i).getZfbShouquan())){
//                    //根据图片地址构建URL
//                    URL url = new URL(pics.get(i).getZfbShouquan());//支付宝授权函
//                    URLConnection conn = url.openConnection();
//                    conn.setReadTimeout(10000);
//                    conn.setConnectTimeout(10000);
//                    conn.connect();
//                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
//                    //创建目录和图片
//                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
//                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "支付宝授权函" + i + ".jpg");
//                    if (!pathFile.exists()) {
//                        pathFile.mkdirs();
//                        file.createNewFile();
//                    }
//                    if (!file.exists()) {
//                        file.createNewFile();
//                    }
//                    //通过流复制图片
//                    FileOutputStream fileOutputStream = new FileOutputStream(file);
//                    ByteArrayOutputStream output = new ByteArrayOutputStream();
//                    byte[] buffer = new byte[1024];
//                    int length;
//                    while ((length = dataInputStream.read(buffer)) > 0) {
//                        output.write(buffer, 0, length);
//                    }
//                    fileOutputStream.write(output.toByteArray());
//                    dataInputStream.close();
//                    fileOutputStream.close();
//                }
//
//            }
//            for (int i = 0; i < pics.size(); i++) {
//
//                if (ToolUtil.isNotEmpty(pics.get(i).getMentouPics())){
//                    //根据图片地址构建URL
//                    URL url = new URL(pics.get(i).getMentouPics());//门头照
//                    URLConnection conn = url.openConnection();
//                    conn.setReadTimeout(10000);
//                    conn.setConnectTimeout(10000);
//                    conn.connect();
//                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
//                    //创建目录和图片
//                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
//                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "门头照" + i + ".jpg");
//                    if (!pathFile.exists()) {
//                        pathFile.mkdirs();
//                        file.createNewFile();
//                    }
//                    if (!file.exists()) {
//                        file.createNewFile();
//                    }
//                    //通过流复制图片
//                    FileOutputStream fileOutputStream = new FileOutputStream(file);
//                    ByteArrayOutputStream output = new ByteArrayOutputStream();
//                    byte[] buffer = new byte[1024];
//                    int length;
//                    while ((length = dataInputStream.read(buffer)) > 0) {
//                        output.write(buffer, 0, length);
//                    }
//                    fileOutputStream.write(output.toByteArray());
//                    dataInputStream.close();
//                    fileOutputStream.close();
//                }
//
//            }
//            for (int i = 0; i < pics.size(); i++) {
//
//                if (ToolUtil.isNotEmpty(pics.get(i).getNeijingPics())){
//                    //根据图片地址构建URL
//                    URL url = new URL(pics.get(i).getNeijingPics().split(",")[0]);//内景照(1)
//                    URLConnection conn = url.openConnection();
//                    conn.setReadTimeout(10000);
//                    conn.setConnectTimeout(10000);
//                    conn.connect();
//                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
//                    //创建目录和图片
//                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
//                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "内景照(1)" + i + ".jpg");
//                    if (!pathFile.exists()) {
//                        pathFile.mkdirs();
//                        file.createNewFile();
//                    }
//                    if (!file.exists()) {
//                        file.createNewFile();
//                    }
//                    //通过流复制图片
//                    FileOutputStream fileOutputStream = new FileOutputStream(file);
//                    ByteArrayOutputStream output = new ByteArrayOutputStream();
//                    byte[] buffer = new byte[1024];
//                    int length;
//                    while ((length = dataInputStream.read(buffer)) > 0) {
//                        output.write(buffer, 0, length);
//                    }
//                    fileOutputStream.write(output.toByteArray());
//                    dataInputStream.close();
//                    fileOutputStream.close();
//                }
//
//            }
//            for (int i = 0; i < pics.size(); i++) {
//
//                if (ToolUtil.isNotEmpty(pics.get(i).getNeijingPics())){
//                    //根据图片地址构建URL
//                    URL url = new URL(pics.get(i).getNeijingPics().split(",")[1]);//内景照(2)
//                    URLConnection conn = url.openConnection();
//                    conn.setReadTimeout(10000);
//                    conn.setConnectTimeout(10000);
//                    conn.connect();
//                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
//                    //创建目录和图片
//                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
//                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "内景照(2)" + i + ".jpg");
//                    if (!pathFile.exists()) {
//                        pathFile.mkdirs();
//                        file.createNewFile();
//                    }
//                    if (!file.exists()) {
//                        file.createNewFile();
//                    }
//                    //通过流复制图片
//                    FileOutputStream fileOutputStream = new FileOutputStream(file);
//                    ByteArrayOutputStream output = new ByteArrayOutputStream();
//                    byte[] buffer = new byte[1024];
//                    int length;
//                    while ((length = dataInputStream.read(buffer)) > 0) {
//                        output.write(buffer, 0, length);
//                    }
//                    fileOutputStream.write(output.toByteArray());
//                    dataInputStream.close();
//                    fileOutputStream.close();
//                }
//
//            }
//
//            File file1 = new File("D:/wsjd/zfb/zfbtp/");//创建文件目录的绝对路径
//            if (!file1.exists()){
//                file1.mkdir();
//            }
//
//            //}
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }




    public void btnDown(String ids, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String id[] = ids.split(",");
            //查图片
            List<GcgWsjd> pics = this.baseMapper.selectPic(id);

            //多个图片下载地址
            File fileMemu = new File("D:/wsjd/zfb/zfbtp/");//输入要删除文件目录的绝对路径
            deleteFile(fileMemu);

            //多个图片下载地址
            for (int i = 0; i < pics.size(); i++) {

                if (ToolUtil.isNotEmpty(pics.get(i).getYingyeZhizhao())){
                    //根据图片地址构建URL
                    URL url = new URL(pics.get(i).getYingyeZhizhao());//营业执照
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());
                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "营业执照" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();

                    //删除服务器上的临时文件
                    File deleteFile = new File(pics.get(i).getMingcheng());
                    deleteFile.delete();
                }

                if (ToolUtil.isNotEmpty(pics.get(i).getShipinXkz())){
                    //根据图片地址构建URL
                    URL url = new URL(pics.get(i).getShipinXkz());//食品经营许可证
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "食品经营许可证" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                }

                if (ToolUtil.isNotEmpty(pics.get(i).getZfbShouquan())){
                    //根据图片地址构建URL
                    URL url = new URL(pics.get(i).getZfbShouquan());//支付宝授权函
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "支付宝授权函" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                }

                if (ToolUtil.isNotEmpty(pics.get(i).getMentouPics())){
                    //根据图片地址构建URL
                    URL url = new URL(pics.get(i).getMentouPics());//门头照
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "门头照" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                }

                if (ToolUtil.isNotEmpty(pics.get(i).getNeijingPics())){
                    //根据图片地址构建URL
                    URL url = new URL(pics.get(i).getNeijingPics().split(",")[0]);//内景照(1)
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "内景照(1)" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                }

                if (ToolUtil.isNotEmpty(pics.get(i).getNeijingPics())){
                    //根据图片地址构建URL
                    URL url = new URL(pics.get(i).getNeijingPics().split(",")[1]);//内景照(2)
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng());//C:\Users\csh\Desktop
                    File file = new File("D:/wsjd/zfb/zfbtp/" + pics.get(i).getMingcheng() + File.separator + "内景照(2)" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                }

            }

            File file1 = new File("D:/wsjd/zfb/zfbtp/");//创建文件目录的绝对路径
            if (!file1.exists()){
                file1.mkdir();
            }

            //}

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public static void deleteFile(File file){
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //打印文件名
            String name = file.getName();
            System.out.println(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }

}
